package cn.com.headfree.base.controller;

import cn.com.headfree.base.common.MyConstant;
import cn.com.headfree.base.service.TDingUserService;
import cn.com.headfree.base.service.TIgwUserService;
import cn.com.headfree.depterprela.service.IDeptErpRelaService;
import cn.com.headfree.entity.IscUser;
import cn.com.headfree.entity.TDeptEmpRela;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.mouldshow.service.IscUserService;
import cn.com.headfree.util.CookieUtil;
import cn.com.headfree.util.RedisClusterUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiSsoGettokenRequest;
import com.dingtalk.api.request.OapiUserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiSsoGettokenResponse;
import com.dingtalk.api.response.OapiUserGetuserinfoResponse;
import com.gta.edu.sdk.util.EhCacheUtil;
import com.gta.edu.sdk.util.IdGen;
import com.gta.edu.sdk.util.StringUtil;
import com.sgcc.demo.service.IscQueryInfo;
import com.taobao.api.ApiException;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class ExBaseController {
    private static final Logger LOG = LogManager.getLogger(ExBaseController.class);

    @Value("${default.dingTalk-client-token_url}")
    private String tokenUrl;
    @Value("${default.dingTalk-client-corpid}")
    private String corpId;
    @Value("${default.dingTalk-client-corpsecret}")
    private String corpsecret;

    @Value("${default.dingTalk-client-appToken_url}")
    private String appTokenUrl;
    @Value("${default.dingTalk-client-appKey}")
    private String appKey;
    @Value("${default.dingTalk-client-appSecret}")
    private String appSecret;

    @Value("${redis.dingdinguser.timelong}")
    private int dingdingUserLoginTime;

    @Autowired
    private TDingUserService tDingUserService;

    @Autowired
    private TIgwUserService tIgwUserService;

    @Autowired
    private IDeptErpRelaService deptErpRelaService;

    @Autowired
    private IscUserService iscUserService;

    @Autowired
    private IscQueryInfo iscQueryInfo;

    public User getLoginUserInfo(HttpServletRequest req) throws Exception {
        User user = new User();
        /*user = (User) req.getSession().getAttribute("loginUser");
        if(user != null && user.getFax() != null){
            return user;
        }
        LOG.info("=======================session中的登录人为==============="+user);
        */
        String account = CookieUtil.getCookie(req,"account");
        if(account == null){
            account = req.getParameter("account");
        }
        LOG.info("===================account值为====================:" + account);
        if (!StringUtils.isBlank(account)) {
            user = tIgwUserService.getLoginUserInfoByAccount(account);
            user.setAccount(account);//i国网登录账号，用来跟综合管理对应
            switch (user.getRemark()){
                case "1":
                    user.setTitle("普通用户");
                    user.setHomePostalCode(MyConstant.USER_ROLETYPE_PUTONG);
                    break;
                case "2":
                    user.setTitle("单位管理员角色");
                    user.setHomePostalCode(MyConstant.USER_ROLETYPE_DANWEI);
                    break;
                case "3":
                    user.setTitle("省管理员角色");
                    user.setHomePostalCode(MyConstant.USER_ROLETYPE_SHEN);
                    break;
            }

            if (user != null) {
                LOG.info("=========fax值为============"+user.getFax());
                List<TDeptEmpRela> orgs = deptErpRelaService.getOrgIdByErpNo(user.getFax());
                if (orgs != null && orgs.size() > 0) {
                    user.setBaseOrgId(orgs.get(0).getOrgId());
                    user.setBaseOrgName(orgs.get(0).getOrgName());
                }
                List<TDeptEmpRela> depts = deptErpRelaService.getDeptInfoByErpNo(user.getFax());
                if (depts != null && depts.size() > 0) {
                    user.setDeptId(depts.get(0).getDeptId());
                    user.setDeptName(depts.get(0).getDeptName());
                }
                //绑定统一权限平台人员Id
                List<IscUser> iscUsers = iscUserService.getIscUserListByFax(user.getFax());
                if(iscUsers != null && iscUsers.size() > 0){
                    user.setId(iscUsers.get(0).getId());//统一权限平台人员Id
                }

            }
            LOG.info("获取当前登录人信息结果：" + net.sf.json.JSONObject.fromObject(user).toString());
            return user;
        }
        /*结束*/

        String code = req.getParameter("code");
        LOG.info("=====================code值为1=========================:"+code);
        if(!StringUtil.isNullOrEmpty(code)){
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.setCode(code);
            request.setHttpMethod("GET");
            OapiUserGetuserinfoResponse response = client.execute(request, this.getAppToken());
            LOG.info("=========================human-manage-ding调用dingtalk=============================");
            String userId = response.getUserid();
            //String userId = "050233171027357952";
            LOG.info("===================userId值为====================:" + userId);
            if (!StringUtils.isBlank(userId)) {
                user = tDingUserService.getLoginUserInfoByUserId(userId);
                user.setUserId(userId);//钉钉用户id，用来跟综合管理对应
                if (user != null) {
                    LOG.info("=========fax值为============"+user.getFax());
                    List<TDeptEmpRela> orgs = deptErpRelaService.getOrgIdByErpNo(user.getFax());
                    if (orgs != null && orgs.size() > 0) {
                        user.setBaseOrgId(orgs.get(0).getOrgId());
                        user.setBaseOrgName(orgs.get(0).getOrgName());
                    }
                    List<TDeptEmpRela> depts = deptErpRelaService.getDeptInfoByErpNo(user.getFax());
                    if (depts != null && depts.size() > 0) {
                        user.setDeptName(depts.get(0).getDeptName());
                    }
                    //绑定统一权限平台人员Id
                    List<IscUser> iscUsers = iscUserService.getIscUserListByFax(user.getFax());
                    if(iscUsers != null && iscUsers.size() > 0){
                        user.setId(iscUsers.get(0).getId());//统一权限平台人员Id
                    }
                    req.getSession().setAttribute("loginUser",user);
                    LOG.info("====================当前登录人为=================="+user);
                }else{
                    throw new Exception("获取登录用户失败！");
                }
            } else {
            }
            return user;
        }

//            user = new User();
//            user.setName("卓文合");
//            user.setFax("11232046");
//            user.setBaseOrgId("10342674");
//            user.setBaseOrgName("国网安徽省电力有限公司信息通信分公司");
//            user.setPrivateIdentityId("146668035021326324");
//            user.setRemark("2");//普通用户
//            user.setTitle("管理员");
//            user.setDeptName("领导干部");
//            user.setHomePostalCode("xt_rz,ixt_dw_admin");
//            user.setId("F2EC41EDCC5F0086E0430A8A018B0086");

        return user;
    }

    public User getIgwLoginUserInfo(HttpServletRequest req) throws Exception {
        User user = new User();
        String account = CookieUtil.getCookie(req,"account");
            /*String iscResult = iscQueryInfo.getUserInfoByTicket(ticket);
            JSONObject iscResultJson = JSON.parseObject(iscResult);
            String account = iscResultJson.getJSONObject("data").getString("account");*/
            //String userId = "050233171027357952";
            LOG.info("===================account值为====================:" + account);
            if (!StringUtils.isBlank(account)) {
                user = tIgwUserService.getLoginUserInfoByAccount(account);
                user.setAccount(account);//i国网登录账号，用来跟综合管理对应
                if (user != null) {
                    LOG.info("=========fax值为============"+user.getFax());
                    List<TDeptEmpRela> orgs = deptErpRelaService.getOrgIdByErpNo(user.getFax());
                    if (orgs != null && orgs.size() > 0) {
                        user.setBaseOrgId(orgs.get(0).getOrgId());
                        user.setBaseOrgName(orgs.get(0).getOrgName());
                    }
                    List<TDeptEmpRela> depts = deptErpRelaService.getDeptInfoByErpNo(user.getFax());
                    if (depts != null && depts.size() > 0) {
                        user.setDeptName(depts.get(0).getDeptName());
                    }
                    //绑定统一权限平台人员Id
                    List<IscUser> iscUsers = iscUserService.getIscUserListByFax(user.getFax());
                    if(iscUsers != null && iscUsers.size() > 0){
                        user.setId(iscUsers.get(0).getId());//统一权限平台人员Id
                    }

                }else{
                    throw new Exception("获取登录用户失败！");
                }

            return user;
        }

        /*user = new User();
        user.setName("卓文合");
        user.setFax("11232046");
        user.setBaseOrgId("10342674");
        user.setBaseOrgName("国网安徽省电力有限公司信息通信分公司");
        user.setPrivateIdentityId("146668035021326324");
        user.setRemark("2");//普通用户
        user.setTitle("管理员");
        user.setDeptName("领导干部");
        user.setHomePostalCode("xt_rz,ixt_dw_admin");
        user.setId("F2EC41EDCC5F0086E0430A8A018B0086");*/

        return user;
    }

    public String getLoginUserId(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String codeStr = CookieUtil.readCookieAndLogon(req,resp);
        LOG.info("================cookie中code值为=========================："+codeStr);
        if(StringUtil.isNullOrEmpty(codeStr) || codeStr.equals("null")){
            String code = req.getParameter("code");
            LOG.info("================code值为2=========================："+code);
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.setCode(code);
            request.setHttpMethod("GET");
            OapiUserGetuserinfoResponse response = client.execute(request, this.getAppToken());
            LOG.info("=========================human-manage-ding调用dingtalk获取用户ID=============================");
            String userId = response.getUserid();
            CookieUtil.saveCookie(userId,resp);
            codeStr = userId;
            LOG.info("================codeStr值为=========================："+codeStr);
        }
        return codeStr;
    }

//    public User getLoginUserInfo(HttpServletRequest req) throws Exception {
//        String code = req.getParameter("code");
//        if(!StringUtil.isNullOrEmpty(code)){
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/getuserinfo");
//            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
//            request.setCode(code);
//            request.setHttpMethod("GET");
//            OapiUserGetuserinfoResponse response = client.execute(request, this.getAppToken());
//            LOG.info("=========================human-manage-ding调用dingtalk=============================");
//            String userId = response.getUserid();
////        String userId = "050233171027357952";
//            LOG.info("===================userId值为====================:" + userId);
//            User user = new User();
//            String dingdingUserString = EhCacheUtil.getValue("dingding-user-info-"+userId);
//            if (!StringUtil.isNullOrEmpty(dingdingUserString)) {
//                user = (User) JSONObject.parse(dingdingUserString);
//                return user;
//            }
//            dingdingUserString = RedisClusterUtil.getInstance().getString("dingding-user-info-"+userId);
//            if (!StringUtil.isNullOrEmpty(dingdingUserString)) {
//                LOG.info("Redis获取字典信息成功！");
//                user = (User) JSONObject.parse(dingdingUserString);
//                EhCacheUtil.put("dingding-user-info-"+userId, JSONObject.toJSONString(user));
//                return user;
//            }
//            if (!StringUtils.isBlank(userId)) {
//                user = tDingUserService.getLoginUserInfoByUserId(userId);
//                if (user != null) {
//                    List<TDeptEmpRela> deptEmpRelas = deptErpRelaService.getOrgIdByErpNo(user.getFax());
//                    if (deptEmpRelas != null && deptEmpRelas.size() > 0) {
//                        user.setBaseOrgId(deptEmpRelas.get(0).getOrgId());
//                        user.setBaseOrgName(deptEmpRelas.get(0).getOrgName());
//                    }
//                    //绑定统一权限平台人员Id
//                    List<IscUser> iscUsers = iscUserService.getIscUserListByFax(user.getFax());
//                    if(iscUsers != null && iscUsers.size() > 0){
//                        user.setPrivateIdentityId(iscUsers.get(0).getId());//统一权限平台人员Id
//                        EhCacheUtil.put("dingding-user-info-"+userId, JSONObject.toJSONString(user));
//                        RedisClusterUtil.getInstance().setString("dingding-user-info-"+userId, JSONObject.toJSONString(user), dingdingUserLoginTime);
//                    }else{
//                        throw new Exception("绑定用户统一权限平台信息失败！");
//                    }
//                }else{
//                    throw new Exception("获取登录用户失败！");
//                }
//            } else {
//                throw new Exception("获取登录用户ID失败，请检查code值问题！" + response.getBody());
//            }
//            return user;
//        }else{
//            throw new Exception("获取登录用户失败，请检查code值问题！");
//        }
//    }

//    protected String getToken() throws ApiException {
//        DingTalkClient client = new DefaultDingTalkClient(this.tokenUrl);
//        OapiSsoGettokenRequest request = new OapiSsoGettokenRequest();
//        request.setCorpid(this.corpId);
//        LOG.info("corpId值为：" + this.corpId);
//        request.setCorpsecret(this.corpsecret);
//        LOG.info("corpsecret值为：" + this.corpsecret);
//        request.setHttpMethod("GET");
//        OapiSsoGettokenResponse response = client.execute(request);
//        String accessTokenStr = response.getBody();
//        JSONObject accessTokenStrJson = JSONObject.parseObject(accessTokenStr);
//        Object accessTokenObj = accessTokenStrJson.get("access_token");
//        if (accessTokenObj != null) {
//            return accessTokenObj.toString();
//        }
//        return null;
//    }

    protected String getAppToken() throws ApiException {
        DefaultDingTalkClient client = new DefaultDingTalkClient(this.appTokenUrl);
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setAppkey(this.appKey);
        LOG.info("appKey值为：" + this.appKey);
        request.setAppsecret(this.appSecret);
        LOG.info("appSecret值为：" + this.appSecret);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = client.execute(request);
        String accessTokenStr = response.getBody();
        JSONObject accessTokenStrJson = JSONObject.parseObject(accessTokenStr);
        Object accessTokenObj = accessTokenStrJson.get("access_token");
        if (accessTokenObj != null) {
            return accessTokenObj.toString();
        }
        return null;
    }



}
